<template>
  <div class="dashboard-container">
    <div class="app-container" />
    <!-- 顶部显示条 -->
    <PageTools :show-before="true">
      <!-- 左侧显示总记录数 -->
      <template v-slot:before>
        <span>总计共: {{ page.total }} 条记录</span>
      </template>
      <!-- 右侧显示按钮，Excel导入  Excel导出  新增员工 -->
      <template v-slot:after>
        <el-button size="small" type="success" @click="$router.push('/import')">Excel导入</el-button>
        <el-button size="small" type="danger" @click="exportExcel">Excel导出</el-button>
        <el-button size="small" type="primary" @click="addRoles">
          <i class="el-icon-plus" />
          新增员工
        </el-button>
      </template>
    </PageTools>
    <!-- 内容表格区域 -->
    <el-table v-loading="loading" border :data="EmployeesList">
      <el-table-column fixed label="序号" width="50px" sortable="" type="index" />
      <el-table-column label="头像" width="120px" sortable="">
        <!-- 使用插槽插入头像 -->
        <template v-slot="{row}">
          <img
            v-imagerror="defaultImg"
            :src="row.staffPhoto"
            style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
            alt=""
            @click="showCodeDialog(row.staffPhoto)"
          >
        </template>
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="120px" sortable="" />
      <el-table-column prop="workNumber" label="工号" width="120px" sortable="" />
      <el-table-column prop="formOfEmployment" label="聘用形式" width="120px" sortable="" :formatter="formatEmpalyMent" />
      <el-table-column prop="departmentName" label="部门" width="300px" sortable="" />
      <el-table-column prop="timeOfEntry" label="入职时间" width="120px" sortable="">
        <!-- 将入职时间进行过滤格式化 -->
        <template v-slot="{row}">
          {{ row.timeOfEntry | formatDate }}
        </template>
      </el-table-column>
      <el-table-column prop="enableState" label="账户状态" width="120" sortable="">
        <template v-slot="{row}">
          <!-- el-switch  开关组件：根据当前的状态来决定是开  还是关 -->
          <el-switch :value="row.enableState===1" />
        </template>
      </el-table-column>
      <el-table-column label="操作" sortable="" fixed="right" width="250">
        <template v-slot="{row}">
          <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
          <el-button type="text" size="small">转正</el-button>
          <el-button type="text" size="small">调岗</el-button>
          <el-button type="text" size="small">离职</el-button>
          <el-button type="text" size="small" @click="assignRoles(row)">角色</el-button>
          <el-button type="text" size="small" @click="delRoles(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 放置分页组件 -->
    <el-row type="flex" justify="center" align="middle" style="height:60px">
      <el-pagination
        :current-page="page.page"
        :page-size="page.size"
        :total="page.total"
        layout="prev,pager,next"
        @current-change="changePage"
      />
    </el-row>
    <!-- 新增员工的弹出层 -->
    <AddEmploy :is-dialog-show.sync="isDialogShow" />
    <!-- 二维码弹出层 -->
    <el-dialog title="二维码" :visible.sync="isCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <AssignRoles ref="assignroles" :is-assign-dialog-show.sync="isAssignDialogShow" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeesListAPI, delEmployeesListAPI } from '@/api/index'
import EmployeesEnum from '../../api/constant/employees'// 引入员工聘用形式的枚举对象
import AddEmploy from './components/add-employ.vue'
import AssignRoles from './components/assign-role.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
export default {
	components: {
		AddEmploy,
		AssignRoles
	},
	data() {
		return {
			EmployeesList: [], // 声明一个变量，保存员工综合信息的数据列表
			page: { // 声明一个对象，保存分页的数据
				page: 1,
				size: 10,
				total: 0
			},
			loading: false, // 显示遮罩层
			isDialogShow: false, // 声明一个变量，控制新增员工弹出层的显示和隐藏
			defaultImg: require('@/assets/common/Eason.webp'),
			isCodeDialog: false, // 声明一个变量，控制二维码弹出层的显示和隐藏
			isAssignDialogShow: false, // 声明一个变量，控制新增角色的弹出层的显示和隐藏
			userId: ''// 声明一个变量，保存当前被点击操作的用户Id

		}
	},
	created() {
		this.getEmployeesList()
	},
	methods: {
		// 调用获取员工信息列表的数据接口《《《《《————————————————————————————————————
		async	getEmployeesList() {
			this.loading = true
			const { total, rows } = await getEmployeesListAPI(this.page)
			this.EmployeesList = rows
			this.page.total = total
			this.loading = false
		},
		// 点击分页组件，切换分页+显示新数据《《《《《——————————————————————————————————
		changePage(newpage) {
			this.page.page = newpage
			this.getEmployeesList()
		},
		// 格式化“聘用形式”的函数《《《《《——————————————————————————————————
		// :formatter属性，是el-table-column自带的属性，用来格式化某一个列的内容，值是一个函数
		formatEmpalyMent(row, column, cellValue, index) {
			const res =	EmployeesEnum.hireType.find(item => item.id === cellValue)
			return res ? res.value : '未知'
		},
		// 点击删除按钮，删除对应的员工数据《《《《《——————————————————————————————————
		async	delRoles(row) {
			try {
				await this.$confirm('确定要删除该员工信息吗？')
				await delEmployeesListAPI(row.id)
				this.getEmployeesList()
				this.$message.success('删除成功！')
			} catch (err) {
				console.log(err);
			}
		},
		addRoles() {
			this.isDialogShow = true
		},
		// 点击导出excel按钮，导出excel表格的函数《《《《《——————————————————————————————————
		exportExcel() {
			// 表头的中英文对照关系
			const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
			import('@/vendor/Export2Excel').then(async excel => {
				// 调用获取员工信息的接口(参数：页码：1页；每页条数：全部总条数)
				const { rows } = await getEmployeesListAPI({ page: 1, size: this.page.total })
				const data = this.formatJson(headers, rows)
				const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
				const merges = ['A1:A2', 'B1:F1', 'G1:G2']
				excel.export_json_to_excel({
					header: Object.keys(headers),
					data,
					filename: '员工工资表',
					multiHeader, // 复杂表头
					merges// 合并单元格
				})
			})
		},
		// excel导出时， 将excel表格中的  表头  和  数据  一一对应的函数《《《《《——————————————————————————————————
		formatJson(headers, rows) {
			return rows.map(item => {
				return Object.keys(headers).map(key => {
					if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
						return formatDate(item[headers[key]])
					} else if (headers[key] === 'formOfEmployment') {
							const obj =	EmployeesEnum.hireType.find(obj => obj.id === item[headers[key]])
							return	obj ? obj.value : '未知'
					}
					return item[headers[key]]
				})
			})
		},
		// 点击头像，显示二维码弹出层《《《《《——————————————————————————————————
		showCodeDialog(url) {
			if (url) {
				this.isCodeDialog = true
				// this.$nextTick()可以在上一次数据更新完毕，页面渲染完毕之后执行
				this.$nextTick(() => {
					QrCode.toCanvas(this.$refs.myCanvas, url)
				})
			} else {
				this.$message.warning('请完成上传头像！')
			}
		},
		// 点击角色按钮，显示新增角色的弹出层
		async	assignRoles(row) {
			this.userId = row.id
			await this.$refs.assignroles.getUserRole(row.id)// 父组件通过ref，获得子组件的实例，可以调用子组件中的全部方法，然后传入id
			this.isAssignDialogShow = true
		}
	}
}
</script>
<style scoped>
::v-deep .el-dialog__header{
	background-color: #5daeff !important;

}
::v-deep .el-dialog__title{
	color: #fff !important;
}
::v-deep .el-dialog__close{
	color: #fff !important;
}

</style>